package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.*;
import com.itheima.service.MemberService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.*;

/**
 * @author Ron
 * @date 2020-03-07 9:41
 */
@RestController
@RequestMapping("/member")
public class MemberController {
    @Reference
    private MemberService memberService;

    //分页展示会员信息
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult page = null;
        try {
            page = memberService.findPage(queryPageBean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return page;
    }


    //    查询健康师信息
    @RequestMapping("/findAll")
    public Result findAll() {
        try {
            List<User> users = memberService.findAll();
            return new Result(true, MessageConstant.QUERY_USER_SUCCESS, users);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_USER_FAIL);
        }

    }

    //新增会员信息
    @RequestMapping("/add")
    public Result addMember(@RequestBody Member member) {
        try {
            memberService.addMember(member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_SETMEAL_FAIL);
        }
        return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);

    }


    //编辑数据回写member
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            Member member = memberService.findById(id);
            return new Result(true, MessageConstant.QUERY_MENU_SUCCESS, member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_MENU_FAIL);
        }
    }

    //编辑会员信息
    @RequestMapping("/edit")
    public Result edit(@RequestBody Member member) {
        try {
            memberService.edit(member);
            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }

    }

    //删除会员信息
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            memberService.delete(id);
        } catch (Exception e) {
            return new Result(false, "当前会员有预约未完成" + MessageConstant.DELETE_CHECKGROUP_FAIL);
        }
        return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
    }

    //导出会员信息数据到Excel并提供客户端下载
    //数据包含会员预约信息
    @RequestMapping("/exportMemberReport")
    public Result exportMemberReport(HttpServletRequest request, HttpServletResponse response, Integer[] memberIds) {
        try{
            List<Map<String,Object>> result = memberService.getMemberReportData(memberIds);
            //动态获取Excel模板文件绝对磁盘路径
            String filePath = request.getSession().getServletContext().getRealPath("/template") + File.separator + "member.xlsx";

            //基于POI在内存中创建一个Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));

            XSSFSheet sheet = excel.getSheetAt(0);

            //取出返回结果数据，准备将报表数据写入到Excel文件中
            //遍历result集合
            List <Map<String, String>> xiuGai=new ArrayList<Map<String, String>>();

            for (int i = 0; i < result.size(); i++) {
                //取出"member"键对应的值member对象
                Member member = (Member) result.get(i).get("member");
                String name = member.getName();
                String sex = member.getSex();
                String phoneNumber = member.getPhoneNumber();
                List<Map<Setmeal,String>> addressAndSetMeal = (List) result.get(i).get("addressAndSetMeal");
                for (int j = 0; j < addressAndSetMeal.size();j++) {
                    Map<String,String> xiuGaiMap=new HashMap<String,String>();
                    String address = "";
                    String CheckGroupColumnName ="";
                    String CheckItemColumnName ="";
                    String setmealName="";
                    Set<Map.Entry<Setmeal, String>> entries = addressAndSetMeal.get(j).entrySet();
                    for (Map.Entry<Setmeal, String> set : entries) {
                        address = set.getValue();
                        Setmeal setmeal = set.getKey();
                        setmealName = setmeal.getName();
                        List<CheckGroup> checkGroups = setmeal.getCheckGroups();
                        for (CheckGroup checkGroup : checkGroups) {
                            String checkGroupName = checkGroup.getName();
                            CheckGroupColumnName=CheckGroupColumnName + checkGroupName+",";
                            List<CheckItem> checkItems = checkGroup.getCheckItems();
                            for (CheckItem checkItem : checkItems) {
                                String checkItemName = checkItem.getName();
                                CheckItemColumnName=CheckItemColumnName+checkItemName+",";
                            }
                        }
                    }
                    xiuGaiMap.put("name",name);
                    if (sex.equals("1")){
                        xiuGaiMap.put("sex","男");
                    }else{
                        xiuGaiMap.put("sex","女");
                    }

                    xiuGaiMap.put("phoneNumber",phoneNumber);
                    xiuGaiMap.put("address",address);
                    xiuGaiMap.put("setmealName",setmealName);
                    xiuGaiMap.put("CheckGroupColumnName",CheckGroupColumnName);
                    xiuGaiMap.put("CheckItemColumnName",CheckItemColumnName);
                    xiuGai.add(xiuGaiMap);

                }
            }
            for (int i = 0; i < xiuGai.size(); i++) {
                XSSFRow row = sheet.createRow(i+3);
                Map<String, String> map = xiuGai.get(i);
                row.createCell(0).setCellValue(map.get("name"));
                row.createCell(1).setCellValue(map.get("sex"));
                row.createCell(2).setCellValue(map.get("phoneNumber"));
                row.createCell(3).setCellValue(map.get("address"));
                row.createCell(4).setCellValue(map.get("setmealName"));
                row.createCell(5).setCellValue(map.get("CheckGroupColumnName"));
                row.createCell(6).setCellValue(map.get("CheckItemColumnName"));

            }


            //创建输出流，用于从服务器写数据到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            excel.write(out);

            out.flush();
            out.close();
            excel.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}